package com.hospital.hospitalsystem.utils;

import com.hospital.hospitalsystem.entity.UserExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import javax.servlet.http.HttpServletRequest;

/**
 * @author qiancheng@cqxyy.net
 * @date 2023/2/21
 */
@Component
public class LoginUtils {
    @Autowired
    private HttpServletRequest request;

    //token密钥
    private static final String TOKEN_SECRET = "LJSBF932GFH9WF9WEGFFGWEPUFWPUFG3Q3D";

    public UserExt getUser(){
        String token = request.getHeader("token");
        return getUser(token);
    }

    public static UserExt getUser(String token){
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(TOKEN_SECRET)
                    .parseClaimsJws(token)
                    .getBody();
            UserExt userExt = new UserExt();
            userExt.setUserId(Integer.toUnsignedLong((Integer) claims.get("userID")));
            userExt.setUserName(claims.getSubject());
            userExt.setUserTime(claims.getIssuedAt());
            userExt.setOverdueTime(claims.getExpiration());
            userExt.setRoles((String)claims.get("role"));
            userExt.setUserUuid((String)claims.get("uuid"));
            return userExt;
        }catch (Exception e){
            throw new RuntimeException("获取用户失败");
        }
    }
}
